package com.itlong.cloud.commons.service;

import com.itlong.cloud.POJO.VO.property.PropertyProjectAmountVO;
import com.itlong.cloud.commons.dao.IUpdateAmountDao;
import com.itlong.cloud.commons.queue.UpdateProjectAmountQueue;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class UpdateProjectAmountService {
    private static final Logger LOG = LoggerFactory.getLogger(UpdateProjectAmountService.class);

    @Autowired
    UpdateProjectAmountQueue updateProjectAmountQueue;

    @Autowired
    IUpdateAmountDao iUpdateAmountDao;

    private ExecutorService cachedThreadPool ; //线程池

    /**
     * <desc>
     *     修改项目可提现余额,实时余额(将请求放入队列)
     * </desc>
     *
     * @param updateProjectAmountInfo 修改信息
     * @return
     * @author Qiang.S
     * @createDate 2018/09/26
     */
    public boolean updateProjectAmount(Map<String,Object> updateProjectAmountInfo){
        try{
            updateProjectAmountQueue.getUpdateProjectAmountQueue().put(updateProjectAmountInfo);
        }catch (Exception e){
            LOG.error("修改项目可提现余额,实时余额加入队列失败！e:" +  e.getMessage());
            return  false;
        }
        return  true;
    }

    /**
     * <desc>
     *     修改项目可提现余额,实时余额
     * </desc>
     *
     * @return
     * @author Qiang.S
     * @createDate 2018/09/24
     */
    private void doUpdateProjectAmount(){
        while (true) {
            try {
                Map<String,Object> str = updateProjectAmountQueue.getUpdateProjectAmountQueue().take();
                String arithmeticFlag = str.get("arithmeticFlag").toString();//运算: 0加,1减
                String amount = str.get("amount").toString();//金额
                String projectId = str.get("projectId").toString();//项目编号
                String updateNameFlag = str.get("updateNameFlag").toString();//更新字段标识: 0可提现余额,1实时余额
                LOG.info(String.format("arithmeticFlag：%s  amount:%s  projectId:%s  updateNameFlag:%s", arithmeticFlag,amount,projectId,updateNameFlag));
                if (!StringUtils.isBlank(arithmeticFlag) && !StringUtils.isBlank(amount) && !StringUtils.isBlank(projectId)) {
                    PropertyProjectAmountVO propertyProjectAmountVO = iUpdateAmountDao.getProjectAmountInfo(projectId);
                    String allowedCashWithdrawl = "";
                    String accountAmount = "";
                    if (propertyProjectAmountVO != null) {
                        if ("0".equals(arithmeticFlag)) {//增加金额
                            if ((propertyProjectAmountVO.getAccountAmount() == null || "".equals(propertyProjectAmountVO.getAccountAmount()))
                                    && ("".equals(updateNameFlag) || "1".equals(updateNameFlag))) {
                                accountAmount = amount;
                            }else if ("".equals(updateNameFlag) || "1".equals(updateNameFlag)){
                                accountAmount = new BigDecimal(amount).add(new BigDecimal(propertyProjectAmountVO.getAccountAmount())).toString();
                            }

                            if ((propertyProjectAmountVO.getAllowedCashWithdrawl() == null || "".equals(propertyProjectAmountVO.getAllowedCashWithdrawl()))
                                    && ("".equals(updateNameFlag) || "0".equals(updateNameFlag))) {
                                allowedCashWithdrawl = amount;
                            }else if ("".equals(updateNameFlag) || "0".equals(updateNameFlag)){
                                allowedCashWithdrawl = new BigDecimal(amount).add(new BigDecimal(propertyProjectAmountVO.getAllowedCashWithdrawl())).toString();
                            }
                        } else if ("1".equals(arithmeticFlag)) {//减少金额
                            if ((propertyProjectAmountVO.getAccountAmount() == null || "".equals(propertyProjectAmountVO.getAccountAmount()))
                                    && ("".equals(updateNameFlag) || "1".equals(updateNameFlag))) {
                               continue;//为空不允许减少
                            }else if ("".equals(updateNameFlag) || "1".equals(updateNameFlag)){
                                accountAmount = new BigDecimal(propertyProjectAmountVO.getAccountAmount()).subtract(new BigDecimal(amount)).toString();
                                if (new Double(accountAmount) < 0) {
                                    LOG.info("出现了负数情况 accountAmount:"+accountAmount);
                                    continue;//不允许减少为负数
                                }
                            }

                            if (propertyProjectAmountVO.getAllowedCashWithdrawl() == null || "".equals(propertyProjectAmountVO.getAllowedCashWithdrawl())
                                    && ("".equals(updateNameFlag) || "0".equals(updateNameFlag))) {
                                continue;//为空不允许减少
                            }else if ("".equals(updateNameFlag) || "0".equals(updateNameFlag)){
                                allowedCashWithdrawl = new BigDecimal(propertyProjectAmountVO.getAllowedCashWithdrawl()).subtract(new BigDecimal(amount)).toString();
                                if (new Double(allowedCashWithdrawl) < 0) {
                                    LOG.info("出现了负数情况 allowedCashWithdrawl:"+allowedCashWithdrawl);
                                    continue;//不允许减少为负数
                                }
                            }
                        }
                        LOG.info("propertyProjectAmountVO:"+propertyProjectAmountVO.toString());
                        LOG.info(String.format("projectId：%s  allowedCashWithdrawl:%s  accountAmount:%s", projectId,allowedCashWithdrawl,accountAmount));
                        iUpdateAmountDao.updateProjectAmount(projectId,allowedCashWithdrawl,accountAmount);
                        Thread.sleep(500);//防止数据库数据不同步,每执行一次等待0.5秒
                    }
                }
            }  catch (Exception e) {
                e.printStackTrace();
                LOG.error("【修改项目可提现余额,实时余额异常】");
            }
        }
    }
    /**
     * <desc>
     *      初始化
     * </desc>
     *
     * @author Qiang.S
     * @createDate 2018/09/24
     */
    @PostConstruct
    public void init(){
        cachedThreadPool = Executors.newSingleThreadExecutor();
            cachedThreadPool.execute(() -> {
                doUpdateProjectAmount();
            });
    }
}
